const router = require('koa-router')()
const query = require("../db/mysql");
const fs = require("fs");
const path = require("path");
const {obj,encrypt, decrypt} = require('../public/util')
const {key,iv} = obj;

router.get('/qa',async function (ctx,next){
  try{
      const id = ctx.query.pId
      let sql = `SELECT * FROM qa where pid = ${id}`
      let data = await query(sql)
      return ctx.body = {
          status:200,
          data:data,
          msg:''
      }
  }catch (err){
      console.error(err)
      return ctx.body = {
          status:500,
          msg:err
      }
  }
})

router.get('/unlocklist',async function (ctx,next){
    try{
        var uid = ctx.query.uId;
        uid = decrypt(uid,key,iv);
        let sql = `SELECT pId FROM unlocklist where uId = ?`
        let data = await query(sql,[uid]);
        return ctx.body = {
            status:200,
            data:data,
            msg:''
        }
    }catch (err){
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }
    }
})

router.get('/scroll',async function(ctx,next){
    try{
        const sId = ctx.query.scrollId
        let sql = `SELECT scrollImage FROM scroll where scrollId = ${sId}`
        let data = await query(sql)
        let imgPath = data.results[0].scrollImage
        let iPath = path.join(__dirname,`/public/data/${imgPath}`)
        let img =  fs.readFileSync(iPath)
        let mimeType = mime.lookup(iPath); //读取图片文件类型
	    ctx.set('content-type', mimeType); 
        return ctx.body = img
    }catch (err){
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }
    }
})

router.get('/sealImage',async function(ctx,next){
    try{
        const seId = ctx.query.sealId
        let sql = `SELECT sealImage FROM seal where sealId = ${seId}`
        let data = await query(sql)
        let imgPath = data.results[0].sealImage
        let name = data.results[0].sealName
        console.log(name)
        let iPath = path.join(__dirname,`/public/data/${imgPath}`)
        let img = fs.readFileSync(iPath)
        let mimeType = mime.lookup(iPath) //读取图片文件类型
	    ctx.set('content-type', mimeType)
        return ctx.body = img
    }catch (err){
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }
    }
})

router.get('/sealName',async function(ctx,next){
    try{
        const seId = ctx.query.sealId
        let sql = `SELECT sealName FROM seal where sealId = ${seId}`
        let data = await query(sql)
        let name = data.results[0].sealName
        console.log(name)
        return ctx.body = name
    }catch (err){
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }
    }
})
//提交用户答题记录
router.post('/record', async (ctx, next)=>{
    var data = ctx.request.body;
    var {pId,brr,uId} = data;
    uId = decrypt(uId,key,iv);
    var brr = JSON.parse(brr);
    try{
        let sql1 = 'select * from record where uId =? and qId =?';
        let sql = `INSERT INTO record(uId,pId,qId,uAnswer,qTrueorFalse) VALUES (?,?,?,?,?)`;
        let sql2 = 'update record set uAnswer= ?,qTrueorFalse= ? where uId =? and qId =?';
        for(var i = 0;i<brr.length;i++){
            var data = await query(sql1,[uId,brr[i].qId])
            if(data != ''){
                await query(sql2,[brr[i].anser,brr[i].torf,uId,brr[i].qId])
            }
            else{
                await query(sql,[uId,pId,brr[i].qId,brr[i].anser,brr[i].torf])
            }
        }
        ctx.status = 200
        return ctx.body = {
            status:200,
            msg:'insert success'
        }
    }catch(err){
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }  
    }
})

router.post('/score', async (ctx, next)=>{
    var data = ctx.request.body;
    var {uId,score} = data;
    uId = decrypt(uId,key,iv);
    try{
        let sql = 'update user set score = ? where uId =?'
        let data = await query(sql,[score,uId])
        ctx.status = 200
        return ctx.body = {
            status:200,
            msg:'update success'
        }
    }catch(err){
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }  
    }
})

router.post('/mywork', async (ctx, next)=>{
    try{
        const {uId,wId,wImage} = ctx.request.body
        let sql = `INSERT INTO collection(uId,pId) VALUES (${uId},${wId},${wImage})`
        await query(sql)
        ctx.status = 200
        return ctx.body = {
            status:200,
            msg:'insert success'
        }
    }catch(err){
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }  
    }
})

module.exports = router
